<?php

namespace wekcms\extend;

use think\template\TagLib;

/*
 * 模板扩展标签
 * */

class cms extends TagLib
{
    /**
     * 定义标签列表
     */
    protected $tags = [
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'list' => ['attr' => 'table,field,where,limit,order,key,val,data', 'close' => 1],//查询
//        'page_list' => ['attr' => 'table,field,where,order,page,url_page_num,key,val,data', 'close' => 1],//分页查询
    ];


    /**
     * @param array $info attr参数集合
     * @param static $content 双标签中间的内容
     */
    public function tagList($info, $content)
    {
        try {
            if (!isset($info['table'])) msg_no('list标签的table参数必填');
            if (!isset($info['field']) || empty($info['field'])) $info['field'] = "*";
            if (!isset($info['limit']) || empty($info['limit'])) $info['limit'] = 10;
            if (!isset($info['key']) || empty($info['key'])) $info['key'] = 'key';
            if (!isset($info['val']) || empty($info['val'])) $info['val'] = 'val';
            if (!isset($info['data']) || empty($info['data'])) $info['data'] = 'data';
            $info['key'] = '$' . $info['key'];
            $info['val'] = '$' . $info['val'];
            $info['data'] = '$' . $info['data'];
            //如果模板标签给了参数
            $order_str = '';
            if (isset($info['order']) || !empty($info['order'])) {
                $order_str = '$db = $db->order("' . $info['order'] . '");';
            }
            $where_str = '';
            if (isset($info['where']) || !empty($info['where'])) {
                $where_str = '$where .= " AND ' . $info['where'] . '";';
            }
            //如果模板标签给了参数
            $parse = <<<str
<?php 
try {
\$db = think\Db::name('{$info['table']}')->field('{$info['field']}');
\$where = 'del=1 AND static=1';
{$order_str}
{$where_str}
\$db = \$db->where(\$where);
{$info['data']} = \$db->limit('{$info['limit']}')->select();
?>
{foreach {$info['data']} as {$info['key']}=>{$info['val']} }
    {$content}
{/foreach}
<?php
} catch (\Exception \$exception) {
            return msg_no(\$exception->getMessage());
}
?>
str;
            return $parse;
        } catch (\Exception $exception) {
            return msg_no($exception->getMessage());
        }
    }


}
